﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace Niaofei.WPF.Control
{
    public static class BorderHelper
    {
        public static bool GetClipRadius(DependencyObject obj)
        {
            return (bool)obj.GetValue(ClipRadiusProperty);
        }

        public static void SetClipRadius(DependencyObject obj, bool value)
        {
            obj.SetValue(ClipRadiusProperty, value);
        }

        /// <summary>
        /// Border圆角裁切问题
        /// </summary>
        public static readonly DependencyProperty ClipRadiusProperty =
            DependencyProperty.RegisterAttached(
                "ClipRadius",
                typeof(bool),
                typeof(Border),
                new PropertyMetadata(default(bool), OnClipRadiusChanges));

        private static void OnClipRadiusChanges(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is Border border)
            {
                if (!border.IsLoaded)
                {
                    border.Loaded += BorderLoaded;
                }

                UpdatingOpactiveMask(border);
            }
        }

        private static void BorderLoaded(object sender, RoutedEventArgs e)
        {
            if (sender is Border border)
            {
                UpdatingOpactiveMask(border);
            }
        }

        private static void UpdatingOpactiveMask(Border border)
        {
            if (!border.IsLoaded)
            {
                return;
            }

            var visualBrush = new VisualBrush();
            var innerBorder = new Border()
            {
                Width = border.ActualWidth,
                Height = border.ActualHeight,
                BorderThickness = border.BorderThickness,
                CornerRadius = border.CornerRadius,
                Background = Brushes.White,
            };

            visualBrush.Visual = innerBorder;
            border.OpacityMask = visualBrush;

            border.Loaded -= BorderLoaded;
        }
    }
}
